#pragma once

#include <string>
#include <cstring>
#include <strings.h>
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>

class UdpServer
{
public:
    UdpServer(uint16_t port) : _sockfd(-1), _port(port), _isrunning(false)
    {
    }

    void InitServer()
    {
         
        // 1.创建 udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);

        // 2.0 填充sockaddr_in 结构
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // 这里sin_addr 里面还有一个结构体

        // 2.1 bind sockfd 和 网络信息
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            exit(1);
        }
       
       
    }

    void Start()
    {
       
        
        _isrunning = true;

        while (true)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            
            if (n > 0)
            {
                buffer[n] = 0;

                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);
            }
        }

        _isrunning = false;
    }

    ~UdpServer()
    {
    }

private:
    uint16_t _port;
    int _sockfd;
    bool _isrunning;
};